﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bzure.Common.Data;
using Bzure.Common.Transactions;
using System.Data;

namespace Bzure.Apps.Security.DataAccess
{
    public abstract class RepositoryBase : Repository
    {
        public RepositoryBase(ITransactionSupport contractProvider)
            : base(contractProvider)
        {
        }
        protected override Entity[] ProcessEntityQueryRequestPaged<Entity>(Bzure.Common.Data.EntityPageQueryRequest<Entity> QueryRequest)
        {
            Dictionary<string, MemberDataMap> MapSet = new Dictionary<string, MemberDataMap>();
            lock (DataMapContainer)
            {
                Dictionary<string, MemberDataMap> MapSetTemp;
                if (DataMapContainer.TryGetValue(typeof(Entity), out MapSetTemp))
                {
                    foreach (KeyValuePair<string, MemberDataMap> kvp in MapSetTemp)
                    {
                        MapSet[kvp.Key] = kvp.Value.Copy();
                    }
                }
                else
                {
                    throw new Exception(string.Format("类型：{0}没有在构建静态构造中初始化实体{1}的数据更新映射", this.GetType().Name, typeof(Entity).Name));
                }
            }
            Delegate queryMap = null;
            if (!QueryMapContainer.TryGetValue(typeof(Entity), out queryMap))
            {
                throw new Exception(string.Format("类型：{0}没有在构建静态构造中初始化实体{1}的数据查询映射", this.GetType().Name, typeof(Entity).Name));
            }
            ResultMapDelegate<Entity> qMap = queryMap as ResultMapDelegate<Entity>;
            //查寻的条件
            List<IDataMemberMap> ConditionDataMemberMapList = new List<IDataMemberMap>();
            foreach (IEntityMemberMap map in QueryRequest.ConditionMap)
            {
                if (map is EntityMemberMap)
                {
                    EntityMemberMap EntityMemberMap = map as EntityMemberMap;
                    MemberDataMap MemberDataMap;
                    if (MapSet.TryGetValue(EntityMemberMap.MemberName, out MemberDataMap))
                    {
                        ConditionDataMemberMapList.Add(new DataMemberMap()
                        {
                            DataFieldName = MemberDataMap.DataFieldName,
                            DataValue = EntityMemberMap.MemberValue,
                            Operator = EntityMemberMap.Operator
                        });
                    }
                }
                else if (map is LogicLinkMap)
                {
                    ConditionDataMemberMapList.Add(map as LogicLinkMap);
                }

            }

            //排序字段
            DataMemberMap OrderFiledmap = default(DataMemberMap);
            if (QueryRequest.OrderByMember != default(EntityMemberMap))
            {
                MemberDataMap mdm;
                if (MapSet.TryGetValue(QueryRequest.OrderByMember.MemberName, out mdm))
                {
                    OrderFiledmap = new DataMemberMap()
                    {
                        DataFieldName = mdm.DataFieldName,
                        DataValue = QueryRequest.OrderByMember.MemberValue,
                        Operator = QueryRequest.OrderByMember.Operator
                    };
                }
            }
            string OrderField = "";
            if (OrderFiledmap != default(DataMemberMap))
            {
                OrderField = string.Format("{0}  {1}", OrderFiledmap.DataFieldName, QueryRequest.OrderTypeString());
            }

            string conditionSql = BuildPageQueryWhere(ConditionDataMemberMapList);

            SqlEntityMap<Entity> ep = new SqlEntityMap<Entity>(this.ContractProvider, "[dbo].[P_BM_GenericPage]");
            ep.SetCommandType(System.Data.CommandType.StoredProcedure);

            List<Entity> list =
            ep.AddString("TableName", this.TableName)
               .AddString("Fields", "*")
               .AddInt("pageSize", QueryRequest.PageSize)
               .AddInt("pageIndex", QueryRequest.PageIndex)
               .AddString("OrderField", OrderField)
               .AddString("sqlWhere", conditionSql)
               .AddInt("TotalPage", QueryRequest.TotalPage).SetDirection(ParameterDirection.Output)
               .AddLong("Return", QueryRequest.TotalRecord).SetDirection(ParameterDirection.ReturnValue)
               .AsList(qMap);
            QueryRequest.TotalPage = (int)ep.GetParamValue("TotalPage");
            //Object o = ep.GetParamValue("Return");
            QueryRequest.TotalRecord = long.Parse(ep.GetParamValue("Return").ToString());
            return list.ToArray();
        }

        string BuildPageQueryWhere(List<IDataMemberMap> DataMemberMaps)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("1=1 ");
            foreach (IDataMemberMap map in DataMemberMaps)
            {
                sb.Append(ParseWhereByValue(map));
            }
            return sb.ToString();
        }
    }
}
